package com.etheart.lyric.util;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.oro.text.regex.MalformedPatternException;
import org.apache.oro.text.regex.PatternCompiler;
import org.apache.oro.text.regex.PatternMatcher;
import org.apache.oro.text.regex.Perl5Compiler;
import org.apache.oro.text.regex.Perl5Matcher;

public class RegexUtils {
	private static final Log logger = LogFactory.getLog(RegexUtils.class);
	public static String[] getMatcheGroups(String partten, String str, int num) {
		Matcher matcher = getMatcher(partten, str);
		try {
			matcher.matches();
			String[] matches = new String[num];
			for (int i = 0; i < num; i++) {
				matches[i] = matcher.group(i+1);
			}
			return matches;
		} catch (Exception e) {
			logger.error("regexUtilsErr:partten="+partten+";str="+str);
			e.printStackTrace();
		}
		return null;
	}
	public static String getMatcheGroup(String partten, String str) {
		Matcher matcher = getMatcher(partten, str);
		try {
			matcher.matches();
			return matcher.group(1);
		} catch (Exception e) {
			logger.error("regexUtilsErr:partten="+partten+";str="+str);
			e.printStackTrace();
		}
		return null;
	}

	public static Matcher getMatcher(String partten, String str) {
		return Pattern.compile(partten).matcher(str);
	}
	
	//一个括号表达式  例如  ([0-9]+)  匹配所有数字  
	public static List<String> getMatcheGroups(String reg, String str) {
		Pattern pattern = Pattern.compile(reg);
		Matcher matcher = pattern.matcher(str);
		List<String > list = new ArrayList<String>();
		// 如果存在匹配项，则执行以下操作
		while (matcher.find()) {
			// 得到这个匹配项中的组数
			int groupCount = matcher.groupCount();
			// 得到每个组中内容
			for (int i = 1; i < groupCount+1; i++) {
				String match = matcher.group(i);
				list.add(match);
			}
		}
		return list;
	}
	
	public static boolean match(String p, String str){
		
		// 用于定义正规表达式对象模板类型  
	      PatternCompiler compiler = new Perl5Compiler();  
	      // 正规表达式比较批配对象  
	      PatternMatcher matcher = new Perl5Matcher();  
	      // 实例大小大小写敏感的正规表达式模板    
	      org.apache.oro.text.regex.Pattern hardPattern;
		try {
			hardPattern = compiler.compile(p);
			 // 返回批配结果  
		      return matcher.contains(str, hardPattern);
		} catch (MalformedPatternException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}  
		return false;
	}
	
	public static void main(String[] args) {
		System.out.println(RegexUtils.match("^http://ting.baidu.com/artist/mainland$", "http://ting.baidu.com/artist/mainland1"));
	}
}
